﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using TBM.Attributes;
using TBM.Filters;

namespace TBM.Controllers
{
    [Authorize]
    [Description("日程安排")]
    public partial class CalendarController : MasterController
    {
        [Description("日程信息")]
        [TBMAuthorize("日程安排", "日程信息")]
        public ActionResult Index()
        {
            return View();
        }

        [ParentAction("Index")]
        [Description("获取日程事件")]
        [TBMAuthorize("日程安排", "获取日程事件")]
        public JsonResult GetEvents(DateTime start, DateTime end)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_GetEvents";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Start", SqlDbType.DateTime);
            cmd.Parameters.Add("@End", SqlDbType.DateTime);

            cmd.Parameters["@UID"].Value = CurrUser.UID;
            cmd.Parameters["@Start"].Value = start;
            cmd.Parameters["@End"].Value = end;

            List<Models.Event> event_base = new List<Models.Event>();
            List<Models.Event> events = new List<Models.Event>();

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    event_base.Add(new Models.Event
                    {
                        ID = (long)dr["ID"],
                        Title = dr["Title"].ToString(),
                        StartTime = Convert.ToDateTime(dr["StartTime"]),
                        Duration = (int)dr["Duration"],
                        Color = dr["Color"].ToString(),
                        TextColor = dr["TextColor"].ToString(),
                        RepeatType = (byte)dr["RepeatType"]
                    });
                }
            }

            foreach (Models.Event item in event_base.Where(a => a.RepeatType != 0))
            {
                DateTime _start = start.AddDays(-7);

                while (_start <= end)
                {
                    Models.Event _item = new Models.Event
                    {
                        ID = item.ID,
                        Title = item.Title,
                        StartTime = item.StartTime,
                        Duration = item.Duration,
                        Color = item.Color,
                        TextColor = item.TextColor,
                        RepeatType = item.RepeatType
                    };
                    _item.StartTime = new DateTime(_start.Year, _start.Month, _start.Day, item.StartTime.Hour, item.StartTime.Minute, item.StartTime.Second);

                    switch (item.RepeatType)
                    {
                        case 1:
                            events.Add(_item);
                            break;
                        case 2:
                            if (item.StartTime.DayOfWeek == _start.DayOfWeek)
                            {
                                events.Add(_item);
                            }
                            break;
                        case 3:
                            if (item.StartTime.Day == _start.Day)
                            {
                                events.Add(_item);
                            }
                            break;
                        case 4:
                            if (item.StartTime.DayOfYear == _start.DayOfYear)
                            {
                                events.Add(_item);
                            }
                            break;
                    }

                    _start = _start.AddDays(1);
                }
            }

            foreach (Models.Event item in event_base.Where(a => a.RepeatType == 0))
            {
                events.Add(item);
            }

            result.Data = new Models.ExecuteResult
            {
                Result = true,
                Code = Core.Lang.CMD_SUCCESS.Code,
                Message = Core.Lang.CMD_SUCCESS.Message,
                Data = events.OrderBy(a => a.StartTime)
            };

            return result;
        }

        /// <summary>
        /// 添加日程事件
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="start">起始时间</param>
        /// <param name="end">终止时间</param>
        /// <param name="color">背景颜色</param>
        /// <param name="textColor">文本颜色</param>
        /// <param name="repeat">重复类型</param>
        /// <returns></returns>
        [ParentAction("Index")]
        [Description("添加日程事件")]
        [TBMAuthorize("日程安排", "添加日程事件")]
        public JsonResult AddEvent(string title, DateTime start, DateTime end, string color, string textColor, short repeat)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = @"insert into dbo.[Events](UID, Title, StartTime, Duration, Color, TextColor, RepeatType)
	                                values(@UID, @Title, @StartTime, @Duration, @Color, @TextColor, @RepeatType)";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Title", SqlDbType.NVarChar, 100);
            cmd.Parameters.Add("@StartTime", SqlDbType.DateTime);
            cmd.Parameters.Add("@Duration", SqlDbType.Int);
            cmd.Parameters.Add("@Color", SqlDbType.Char, 7);
            cmd.Parameters.Add("@TextColor", SqlDbType.Char, 7);
            cmd.Parameters.Add("@RepeatType", SqlDbType.TinyInt);

            int Duration = (int)(end - start).TotalMinutes;

            // 事件标题不能为空
            if (String.IsNullOrEmpty(title))
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = false,
                    Code = Core.Lang.EVENT_CANNOT_EMPTY.Code,
                    Message = Core.Lang.EVENT_CANNOT_EMPTY.Message
                };

                return result;
            }

            // 事件结束时间不能小于开始时间
            if (end < start)
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = false,
                    Code = Core.Lang.EVENT_ENDTIME_ERROR.Code,
                    Message = Core.Lang.EVENT_ENDTIME_ERROR.Message
                };

                return result;
            }

            // 颜色格式必须正确
            Regex r = new Regex("^#([abcdef0-9]{3}||[abcdef0-9]{6})$");

            if (!r.IsMatch(color) || !r.IsMatch(textColor))
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = false,
                    Code = Core.Lang.COLOR_FORMAT_ERROR.Code,
                    Message = Core.Lang.COLOR_FORMAT_ERROR.Message
                };

                return result;
            }

            if (
                    (repeat == 1 && Duration > 1440) ||
                    (repeat == 2 && Duration > 10080) ||
                    (repeat == 3 && Duration > 44640) ||
                    (repeat == 4 && Duration > 527040)
                )
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = false,
                    Code = Core.Lang.EVENT_DURATION_ERROR.Code,
                    Message = Core.Lang.EVENT_DURATION_ERROR.Message
                };

                return result;
            }

            cmd.Parameters["@UID"].Value = CurrUser.UID;
            cmd.Parameters["@Title"].Value = title;
            cmd.Parameters["@StartTime"].Value = start;
            cmd.Parameters["@Duration"].Value = Duration;
            cmd.Parameters["@Color"].Value = color;
            cmd.Parameters["@TextColor"].Value = textColor;
            cmd.Parameters["@RepeatType"].Value = repeat;

            if (cmd.ExecuteNonQuery() > 0)
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = true,
                    Code = Core.Lang.EVENT_ADD_SUCCESS.Code,
                    Message = Core.Lang.EVENT_ADD_SUCCESS.Message
                };
            }
            else
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = false,
                    Code = Core.Lang.EVENT_ADD_FAILED.Code,
                    Message = Core.Lang.EVENT_ADD_FAILED.Message
                };
            }

            return result;
        }
    }
}
